package com.meiyou.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.meiyou.mapper.MeiyouHongbaoMapper;
import com.meiyou.mapper.MeiyouUserMapper;
import com.meiyou.pojo.MeiyouHongbao;
import com.meiyou.pojo.MeiyouUser;

import com.meiyou.service.TecentService;
import com.meiyou.utils.Context;
import com.meiyou.utils.HttpUtils;
import com.meiyou.utils.Msg;
import com.sun.jmx.snmp.Timestamp;
import com.tls.tls_sigature.tls_sigature;
import com.tls.tls_sigature.tls_sigature.GenTLSSignatureResult;

import net.sf.json.JSONObject;

@Service
public class TencentServiceImpl implements TecentService {

	@Autowired
	MeiyouHongbaoMapper hongbaoMapper;
	@Autowired
	MeiyouUserMapper userMapper;

	/**
	 * 判断用户是否登录
	 */
	public boolean managerLogin(HttpServletRequest req) {
		if (req.getSession().getAttribute("user") != null) {
			return true;
		} else {
			return false;
		}
	}

	public boolean registTencent(MeiyouUser user) {

		CloseableHttpClient client;
		CloseableHttpResponse response;

		/**
		 * 随机数生成
		 */
		Random rand = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 1; i <= 32; i++) {
			int randNum = rand.nextInt(9) + 1;
			String num = randNum + "";
			sb = sb.append(num);
		}
		String random = String.valueOf(sb); // 32未随机数

		GenTLSSignatureResult result = tls_sigature.genSig(Context.SDKAPPID, Context.IDENTIFIER, Context.PRIKEY);
		String usersig = result.urlSig; // 管理员账号签名

		/**
		 * 接口调用地址
		 */
		String URL = "https://console.tim.qq.com/v4/im_open_login_svc/account_import?sdkappid=" + Context.SDKAPPID
				+ "&identifier=" + Context.IDENTIFIER + "&usersig=" + usersig + "&random=" + random
				+ "&contenttype=json";
		// TODO Auto-generated method stub

		HttpPost post = new HttpPost(URL);

		ObjectMapper objectmapper = new ObjectMapper();
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("Identifier", user.getuCount());
		if(user.getuName()!=null&&!user.getuName().equals("")) {
			data.put("Nick",user.getuName());
		}
		if(user.getuImg()!=null&&!user.getuImg().equals("")) {
			data.put("FaceUrl", user.getuImg());
		}
		HttpEntity entity;
		try {
			entity = new StringEntity(objectmapper.writeValueAsString(data), "utf-8");
			post.setEntity(entity);
			client = HttpClients.createDefault();
			response = client.execute(post);
			HttpEntity repentity = response.getEntity();
			String resresult = EntityUtils.toString(repentity);

			JSONObject json = JSONObject.fromObject(resresult);
            System.out.println("注册腾讯云："+json.toString());
			if (json.get("ActionStatus").equals("OK")) {
				Boolean re =setAddFriMode(user.getuCount(),"AllowType_Type_NeedConfirm");//设置加好友须经同意
				if(!re) {
					return false;
				}else {
					return true;
				}
			} else {
				return false;
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return false;
	}

	public boolean userSendMsg(String fromUser, String toUser, String context, Integer syncOtherMachine) {
		// TODO Auto-generated method stub

		CloseableHttpClient client;
		CloseableHttpResponse response;
		/**
		 * 随机数生成
		 */
		Random rand = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 1; i <= 32; i++) {
			int randNum = rand.nextInt(9) + 1;
			String num = randNum + "";
			sb = sb.append(num);
		}
		String random = String.valueOf(sb); // 32未随机数
		String usersig = tls_sigature.genSig(Context.SDKAPPID, Context.IDENTIFIER, Context.PRIKEY).urlSig;
		String URL = "https://console.tim.qq.com/v4/openim/sendmsg?sdkappid=" + Context.SDKAPPID + "&identifier="
				+ Context.IDENTIFIER + "&usersig=" + usersig + "&random=" + random + "&contenttype=json";

		HttpPost post = new HttpPost(URL);
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("SyncOtherMachine", syncOtherMachine);
		map.put("From_Account", fromUser);
		map.put("To_Account", toUser);

		StringBuffer msgrandom = new StringBuffer();
		for (int i = 1; i <= 9; i++) {
			int randNum = rand.nextInt(9) + 1;
			String num = randNum + "";
			msgrandom = msgrandom.append(num);
		}

		map.put("MsgRandom", Integer.parseInt(String.valueOf(msgrandom)));
		List<Map<String, Object>> msgBody = new ArrayList<Map<String, Object>>();
		Map<String, Object> body = new HashMap<String, Object>();
		body.put("MsgType", "TIMTextElem");
		Map<String, String> msg = new HashMap<String, String>();
		msg.put("Text", context);
		body.put("MsgContent", msg);
		msgBody.add(body);
		map.put("MsgBody", msgBody);

		try {
			HttpEntity entity = new StringEntity(mapper.writeValueAsString(map));
			post.setEntity(entity);
			client = HttpClients.createDefault();

			response = client.execute(post);

			String result = EntityUtils.toString(response.getEntity());
			JSONObject json = JSONObject.fromObject(result);

			if (json.get("ActionStatus").equals("OK")) {
				return true;
			} else {
				return false;
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return false;
	}

	/**
	 * 发送表情包消息
	 */
	public boolean userSendBiaoQingMsg(String fromUser, String toUser, int index, Integer SyncOtherMachine) {
		// TODO Auto-generated method stub
		CloseableHttpClient client;
		CloseableHttpResponse response;

		/**
		 * 随机数生成
		 */
		Random rand = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 1; i <= 32; i++) {
			int randNum = rand.nextInt(9) + 1;
			String num = randNum + "";
			sb = sb.append(num);
		}
		String random = String.valueOf(sb); // 32未随机数
		String usersig = tls_sigature.genSig(Context.SDKAPPID, Context.IDENTIFIER, Context.PRIKEY).urlSig;
		String URL = "https://console.tim.qq.com/v4/openim/sendmsg?sdkappid=" + Context.SDKAPPID + "&identifier="
				+ Context.IDENTIFIER + "&usersig=" + usersig + "&random=" + random + "&contenttype=json";

		HttpPost post = new HttpPost(URL);
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("SyncOtherMachine", SyncOtherMachine);
		map.put("From_Account", fromUser);
		map.put("To_Account", toUser);

		StringBuffer msgrandom = new StringBuffer();
		for (int i = 1; i <= 9; i++) {
			int randNum = rand.nextInt(9) + 1;
			String num = randNum + "";
			msgrandom = msgrandom.append(num);
		}

		map.put("MsgRandom", Integer.parseInt(String.valueOf(msgrandom)));
		List<Map<String, Object>> msgBody = new ArrayList<Map<String, Object>>();
		Map<String, Object> body = new HashMap<String, Object>();

		body.put("MsgType", "TIMTextElem");
		Map<String, Object> msg = new HashMap<String, Object>();
		msg.put("Index", index);
		msg.put("Data", null);
		body.put("MsgContent", msg);
		msgBody.add(body);
		map.put("MsgBody", msgBody);

		try {
			HttpEntity entity = new StringEntity(mapper.writeValueAsString(map));
			post.setEntity(entity);
			client = HttpClients.createDefault();

			response = client.execute(post);

			String result = EntityUtils.toString(response.getEntity());
			JSONObject json = JSONObject.fromObject(result);

			if (json.get("ActionStatus").equals("OK")) {
				return true;
			} else {
				return false;
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return false;
	}

	public boolean userSendWeiZhiMsg(String fromUser, String toUser, String desc, double latitude, double longitude,
			Integer syncOtherMachine) {
		// TODO Auto-generated method stub
		CloseableHttpClient client;
		CloseableHttpResponse response;

		/**
		 * 随机数生成
		 */
		Random rand = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 1; i <= 32; i++) {
			int randNum = rand.nextInt(9) + 1;
			String num = randNum + "";
			sb = sb.append(num);
		}
		String random = String.valueOf(sb); // 32未随机数
		String usersig = tls_sigature.genSig(Context.SDKAPPID, Context.IDENTIFIER, Context.PRIKEY).urlSig;
		String URL = "https://console.tim.qq.com/v4/openim/sendmsg?sdkappid=" + Context.SDKAPPID + "&identifier="
				+ Context.IDENTIFIER + "&usersig=" + usersig + "&random=" + random + "&contenttype=json";

		HttpPost post = new HttpPost(URL);
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("SyncOtherMachine", syncOtherMachine);
		map.put("From_Account", fromUser);
		map.put("To_Account", toUser);

		StringBuffer msgrandom = new StringBuffer();
		for (int i = 1; i <= 9; i++) {
			int randNum = rand.nextInt(9) + 1;
			String num = randNum + "";
			msgrandom = msgrandom.append(num);
		}

		map.put("MsgRandom", Integer.parseInt(String.valueOf(msgrandom)));
		List<Map<String, Object>> msgBody = new ArrayList<Map<String, Object>>();
		Map<String, Object> body = new HashMap<String, Object>();

		body.put("MsgType", "TIMTextElem");
		Map<String, Object> msg = new HashMap<String, Object>();
		msg.put("Desc", desc);
		msg.put("Latitude", latitude);
		msg.put("Longitude", longitude);
		body.put("MsgContent", msg);
		msgBody.add(body);
		map.put("MsgBody", msgBody);

		try {
			HttpEntity entity = new StringEntity(mapper.writeValueAsString(map));
			post.setEntity(entity);
			client = HttpClients.createDefault();

			response = client.execute(post);

			String result = EntityUtils.toString(response.getEntity());
			JSONObject json = JSONObject.fromObject(result);

			if (json.get("ActionStatus").equals("OK")) {
				return true;
			} else {
				return false;
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return false;
	}

	/**
	 * 添加好友
	 */

	public boolean addFriend(String fromaccount, String toaccount) {
		// TODO Auto-generated method stub
		CloseableHttpClient client;
		CloseableHttpResponse response;

		/**
		 * 随机数生成
		 */

		Random rand = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 1; i <= 32; i++) {
			int randNum = rand.nextInt(9) + 1;
			String num = randNum + "";
			sb = sb.append(num);
		}
		String random = String.valueOf(sb); // 32未随机数
		String usersig = tls_sigature.genSig(Context.SDKAPPID, Context.IDENTIFIER, Context.PRIKEY).urlSig;

		String url = "https://console.tim.qq.com/v4/sns/friend_add?sdkappid=" + Context.SDKAPPID + "&&identifier="
				+ Context.IDENTIFIER + "&usersig=" + usersig + "&random=" + random + "&contenttype=json";

		HttpPost post = new HttpPost(url);
		ObjectMapper objectMapper = new ObjectMapper();
		Map<String, Object> reqbody = new HashMap<String, Object>();
		List<Object> list = new ArrayList<Object>();
		Map<String, String> map = new HashMap<String, String>();
		map.put("To_Account", toaccount);
		map.put("AddSource", "AddSource_Type_Meiyou");
		list.add(map);
		reqbody.put("From_Account", fromaccount);
		reqbody.put("AddFriendItem", list);
		reqbody.put("AddType", "Add_Type_Both");
		reqbody.put("ForceAddFlags", 0);

		try {
			HttpEntity entity = new StringEntity(objectMapper.writeValueAsString(reqbody));

			post.setEntity(entity);
			client = HttpClients.createDefault();

			response = client.execute(post);
			JSONObject json = JSONObject.fromObject(EntityUtils.toString(response.getEntity()));
			if (json.get("ActionStatus").equals("OK")) {
				return true;
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return false;
	}

	/**
	 * 单向删除好友
	 */

	public boolean deleteFriend(String fromaccount, String toaccount) {
		// TODO Auto-generated method stub

		CloseableHttpClient client;
		CloseableHttpResponse response;

		Random rand = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 1; i <= 32; i++) {
			int randNum = rand.nextInt(9) + 1;
			String num = randNum + "";
			sb = sb.append(num);
		}
		String random = String.valueOf(sb); // 32未随机数
		String usersig = tls_sigature.genSig(Context.SDKAPPID, Context.IDENTIFIER, Context.PRIKEY).urlSig;

		String url = "https://console.tim.qq.com/v4/sns/friend_delete?sdkappid=" + Context.SDKAPPID + "&identifier="
				+ Context.IDENTIFIER + "&usersig=" + usersig + "&random=" + random + "&contenttype=json";
		HttpPost post = new HttpPost(url);

		ObjectMapper objectMapper = new ObjectMapper();
		Map<String, Object> resbody = new HashMap<String, Object>();
		List<String> list = new ArrayList<String>();
		list.add(toaccount);
		resbody.put("From_Account", fromaccount);
		resbody.put("To_Account", list);
		resbody.put("DeleteType", "Delete_Type_Both");
		try {
			post.setEntity(new StringEntity(objectMapper.writeValueAsString(resbody)));
			client = HttpClients.createDefault();
			response = client.execute(post);
			JSONObject json = JSONObject.fromObject(EntityUtils.toString(response.getEntity()));
			if (json.get("ActionStatus").equals("OK")) {
				return true;
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return false;
	}

	/**
	 * 添加黑名单
	 */
	
	public boolean addBlackList(String fromAcount, String toAcount) {
		// TODO Auto-generated method stub
		CloseableHttpClient client;
		CloseableHttpResponse response;

		Random rand = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 1; i <= 32; i++) {
			int randNum = rand.nextInt(9) + 1;
			String num = randNum + "";
			sb = sb.append(num);
		}
		String random = String.valueOf(sb); // 32未随机数
		String usersig = tls_sigature.genSig(Context.SDKAPPID, Context.IDENTIFIER, Context.PRIKEY).urlSig;

		String url = "https://console.tim.qq.com/v4/sns/black_list_add?sdkappid=" + Context.SDKAPPID + "&identifier="
				+ Context.IDENTIFIER + "&usersig=" + usersig + "&random=" + random + "&contenttype=json";
		HttpPost post = new HttpPost(url);

		ObjectMapper objectMapper = new ObjectMapper();
		Map<String, Object> resbody = new HashMap<String, Object>();
		resbody.put("From_Account", fromAcount);
		List<String> li = new ArrayList<String>();
		li.add(toAcount);
		resbody.put("To_Account",li);
		try {
			post.setEntity(new StringEntity(objectMapper.writeValueAsString(resbody)));
			client = HttpClients.createDefault();
			response = client.execute(post);
			JSONObject json = JSONObject.fromObject(EntityUtils.toString(response.getEntity()));
			if (json.get("ActionStatus").equals("OK")) {
				return true;
			}else {
				System.out.println("添加失败"+json);
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return false;
	}

	
	public Msg sendHongbao(String fromcount, String tocount, Double meijin) {
		Msg msg;
		// TODO Auto-generated method stub

		Double hasmeijin = userMapper.selMeijin(fromcount);
		System.out.println(fromcount + "拥有资金" + hasmeijin);
		if (hasmeijin >= meijin) {
			if (userMapper.updDelMeijin(meijin, fromcount) >= 1) {
				if (userMapper.updAddMeijin(meijin, tocount) >= 1) {
					MeiyouHongbao hongbao = new MeiyouHongbao();
					hongbao.sethUCount(fromcount);
					hongbao.sethUBcount(tocount);
					hongbao.sethState("完成");
					hongbao.sethMeijin(meijin);
					if (hongbaoMapper.insHongbao(hongbao) >= 1) {
						msg = Msg.success();
						return msg;
					}
				}
			}
		} else {
			msg = Msg.fail();
			msg.setMsg("账号余额不足");
			return msg;
		}

		msg = Msg.fail();

		return msg;
	}

	
	public Msg setUserInfo(MeiyouUser user) {
		// TODO Auto-generated method stub
		Msg msg;
		Random rand = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 1; i <= 32; i++) {
			int randNum = rand.nextInt(9) + 1;
			String num = randNum + "";
			sb = sb.append(num);
		}
		String random = String.valueOf(sb); // 32未随机数
		String usersig = tls_sigature.genSig(Context.SDKAPPID, Context.IDENTIFIER, Context.PRIKEY).urlSig;
		String URL = "https://console.tim.qq.com/v4/profile/portrait_set?sdkappid=" + Context.SDKAPPID + "&identifier="+ Context.IDENTIFIER +"&usersig=" + usersig + "&random=" + random + "&contenttype=json";	
       
        Map<String,Object> map = new HashMap<String,Object>();
        List<Object> list = new ArrayList<Object>();
        if(user.getuName()!=null) {
        	//昵称
            Map<String,Object> nickname = new HashMap<String,Object>();
            nickname.put("Tag", "Tag_Profile_IM_Nick");
            nickname.put("Value", user.getuName());
            list.add(nickname);

        }
        if(user.getuSex()!=null) {
        	//性别
            Map<String,Object> sex = new HashMap<String,Object>();
            
            sex.put("Tag", "Tag_Profile_IM_Gender");
            if(user.getuSex().equals("男")) {
            	sex.put("Value", "Gender_Type_Female");
            }else {
            	sex.put("Value", "Gender_Type_Male");
            }
            
            list.add(sex);
        }
        if(user.getQianming()!=null) {
        	//签名
            Map<String,Object> qianming = new HashMap<String,Object>();
            qianming.put("Tag", "Tag_Profile_IM_SelfSignature");
            qianming.put("Value", user.getQianming());
            list.add(qianming);
        }
        if(user.getuImg()!=null) {
        	//头像
            Map<String,Object> img = new HashMap<String,Object>();
            img.put("Tag", "Tag_Profile_IM_Image");
            img.put("Value", user.getuImg());
            list.add(img);
        }
        map.put("From_Account", user.getuCount());
        map.put("ProfileItem", list);
		JSONObject json = HttpUtils.postToJSONObject(URL, map);
		
		if(json.getString("ActionStatus").equals("OK")) {
			msg = Msg.success();
			return msg;
		}else {
			msg = Msg.fail();
			msg.setMsg("IM错误码："+json.getString("ErrorCode")+","+"IM错误信息："+json.getString("ErrorInfo"));
			return msg;
		}
		
	}
	
	/**
	 * 设置用户加好友方式
	 * @param account
	 * @param mode
	 * @return
	 */
	private Boolean setAddFriMode(String account,String mode) {
		Random rand = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 1; i <= 32; i++) {
			int randNum = rand.nextInt(9) + 1;
			String num = randNum + "";
			sb = sb.append(num);
		}
		String random = String.valueOf(sb); // 32未随机数
		String usersig = tls_sigature.genSig(Context.SDKAPPID, Context.IDENTIFIER, Context.PRIKEY).urlSig;
		String url = "https://console.tim.qq.com/v4/profile/portrait_set?sdkappid="+Context.VIDEOAPPID+"&identifier="+Context.IDENTIFIER+"&usersig="+usersig+"&random="+random+"&contenttype=json";
		Map<String,Object> map = new HashMap<String,Object>();
		Map<String,Object> profileItem = new HashMap<String,Object>();
		profileItem.put("Tag","Tag_Profile_IM_AllowType");
		profileItem.put("Value", mode);
		List<Object> list = new ArrayList<Object>();
		list.add(profileItem);
		map.put("From_Account", account);
		map.put("ProfileItem", list);
		JSONObject object = HttpUtils.postToJSONObject(url, map);
		String result = object.getString("ActionStatus");
		System.out.println("设置验证方式："+object.toString());
		if(result.equals("OK")) {
			return true;
		}else {
			return false;
		}
	}
}
